package com.atguigu.webadmin.service.impl;

import com.atguigu.common.minio.MinioProperties;
import com.atguigu.webadmin.service.FileService;
import io.minio.*;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Author 梅超凡
 * @Date 2024/11/12~20:22
 * @Description 文件服务实现类
*/
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioProperties properties;

    @Autowired
    private MinioClient client;

    /**
     * @Author 梅超凡
     * @Date 2024/11/18~20:59
     * @Description 上传文件方法逻辑
    */
    @SneakyThrows
    @Override
    @CrossOrigin
    public String upload(MultipartFile file) {
        //判断存储桶是否存在
        boolean bucketExists = client.bucketExists(
                BucketExistsArgs.builder().bucket(
                        properties.getBucketName()).build());
        //如果不存在就创建
        if (!bucketExists) {
            client.makeBucket(MakeBucketArgs.builder()
                    .bucket(properties.getBucketName()).build());
            client.setBucketPolicy(SetBucketPolicyArgs.builder()
                    .bucket(properties.getBucketName())
                    .config(createBucketPolicyConfig(properties.getBucketName())).build());
        }
            //生成文件名
            String filename = new SimpleDateFormat("yyyyMMdd")
                    .format(new Date()) + "/"
                    + UUID.randomUUID() + "-"
                    + file.getOriginalFilename();
            //上传文件
            client.putObject(PutObjectArgs.builder().
                    bucket(properties.getBucketName()).
                    object(filename).
                    stream(file.getInputStream(), file.getSize(), -1).
                    contentType(file.getContentType()).build());
            //返回文件访问路径
            return String.join("/", properties.getEndpoint(), properties.getBucketName(),
                    filename);
    }

    /**
     * @Author 梅超凡
     * @Date 2024/11/15~10:12
     * @Description  创建存储桶的策略
    */
    private String createBucketPolicyConfig(String bucketName) {

        return """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """.formatted(bucketName);
    }
}
